package sjc;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooDefs;

public class ChildrenWatcherDemo {
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3, Integer.MAX_VALUE);
        CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.72.133:2181", 3000, 3000, retryPolicy);
        client.start();

        System.out.println("完成zookeeper的链接。。");
        client.create()
                .creatingParentsIfNeeded()  // 递归创建,自动创建父节点
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) // 设置ACL
                .forPath("/test", "123456".getBytes());

        System.out.println("创建持久节点 /test");

        //  只有第1次 子节点的变化，才能有通知
        client.getChildren().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {
                System.out.println("收到 zookeeper 通知 " + event);
            }
        })
                // 针对的是getChildren让它在后台运行，异步执行，
                // 执行完毕之后获取到了 /test的children, 通过后台回调的方式通知你
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println("收到后台的回调通知 " + event);
                    }
                }).forPath("/test");

        System.out.println("对持久节点‘/test’ 注册watcher 和 callback......");

        Thread.sleep(Integer.MAX_VALUE);
    }
}
